package com.example.springblog.config;

import com.example.springblog.model.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

//设置统一返回结果
@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        //设置统一返回结果。如果有哪些不需要返回。可以使用returnType来判断。
        return true;
    }

    @SneakyThrows //可以省略try-catch 自动抛出异常
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        //对body做一些判断，如果是Result类型，就不需要再次嵌套result
        if(body instanceof Result){
            return body;
        }
        //如果是String 类型，就需要转换为对象类型，防止客户端解析错误
        if(body instanceof String){
            ObjectMapper mapper = new ObjectMapper();
            return mapper.writeValueAsString(Result.success(body));
        }
        return Result.success(body);
    }
}
